(function(){
	var defaults = {
		"appId": null,
		"timeStamp": null,
		"nonceStr": null,
		"package": null,
		"signType": "MD5",
		"paySign": null,
		"returnUrl": null
	}
	
	var prepareWeixinPay = function(data){
		var readyFunc = function(){
			beginPay(data);
		}
		if (typeof WeixinJSBridge == "undefined"){
		   if( document.addEventListener ){
		       document.addEventListener('WeixinJSBridgeReady', readyFunc, false);
		   }else if (document.attachEvent){
		       document.attachEvent('WeixinJSBridgeReady', readyFunc); 
		       document.attachEvent('onWeixinJSBridgeReady', readyFunc);
		   }
		}else{
			console.log("2")
		   beginPay(data);
		}
	}
	
	var beginPay = function(data){
		loader.close();
		console.log(data);
		 WeixinJSBridge.invoke(
	       'getBrandWCPayRequest', data,
	       function(res){
	           if(res.err_msg == "get_brand_wcpay_request:ok" ) {
	           		if(!defaults.returnUrl){
		           		history.go(-1);//TODO 跳转主页会员状态绑定手机弹出框
	           		}else{
	           			window.location = defaults.returnUrl+"?param=isVip";
	           		}
	           }else{
	           		history.go(-1);
	           }     // 使用以上方式判断前端返回,微信团队郑重提示：res.err_msg将在用户支付成功后返回    ok，但并不保证它绝对可靠。
	       }
	  	 ); 
	}
	var loader = null;
//	var xxlUrl = "http://cjj.tunnel.qydev.com/xxl/";
	var doWeixinPayBusiness = function(paymentData, returnUrl,success){
		defaults.returnUrl = returnUrl;
		$.getJSON(mrjyUrl + "common/payment/doScanPayBusiness.do",{
			"name": paymentData.name,
			"money": paymentData.money,
			"code": paymentData.orderCode,
			"className": paymentData.className,
			"wxnotify_url": paymentData.wxnotify_url,
			"messageString": "yes",
			"openid": paymentData.openid
		},function(data){
			if(data.messageString == "success"){
				var payObj = {
					"appId": data.appId,
					"timeStamp": data.timeStamp,
					"nonceStr": data.nonceStr,
					"package": data.package,
					"signType": data.signType,
					"paySign": data.paySign
				}
				console.log(data)
                if(success){
				    success(data);
                }
				// prepareWeixinPay(payObj)
                // return data;
			}else{
				loader.close();
				$.dialog({
					content:"微信支付请求失败！",
					title:"alert",
					ok:function(){
						window.location = "../weClasses/weClasses.html";
					}
				});
//				history.go(-1);
			}
		});
	}
	var a = {
		"prepareWeixinPay": prepareWeixinPay,
		"doWeixinPayBusiness": doWeixinPayBusiness,
	}
	
	window.weixinPay = a;
})()
